#include "sys_common.h"
#include "liblog.h"

static void (*custom_log_cb)(const int, const char *, const int) = NULL;

void liblog_debug(const int fd, const char *msg, const int size)
{
	if(custom_log_cb)
		custom_log_cb(fd, msg, size);
	else 
		write(fd, msg, size);
}

void liblog_callback_set(void (*cb) (const int, const char *, const int)) 
{
	custom_log_cb = cb;
}

void liblog_log(const char *fmt, ...)
{
	char new_format[MAX_BUFFER];
	time_t now = time(NULL);
	char buf[MAX_BUFFER];
	char msg[MAX_BUFFER];
	int res;
    
	mkrfc1123_r(now, buf, MAX_BUFFER);
	va_list  va;
	va_start(va, fmt);
	snprintf(new_format, MAX_BUFFER - 1 ,  "[%s] %s", buf, fmt);
	if((res = vsnprintf(msg, MAX_BUFFER - 1, new_format, va)) < 0)
		fprintf(stderr, "Warning. [%s %d] %s\n", __FILE__, __LINE__, strerror(errno));
	va_end(va);
	liblog_debug(0, msg, res);
}
